package com.stu.thread.demo.producer_consumer_model;

import com.google.common.collect.Queues;
import lombok.extern.slf4j.Slf4j;

import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @projectName: learn_used_code
 * @packageName: com.stu.thread.demo.producer_consumer_model
 * @className: com.stu.thread.demo.producer_consumer_model-> ThreadManagerService2
 * @createDate: 2022-03-12 17:17
 * @author: ZhangSheng
 * @version: 1.0
 * @description:
 */


@Slf4j
public class ThreadManagerService2 {

    private int max = 10;
    private Queue<String> queue = Queues.newLinkedBlockingQueue();
    private ReentrantLock lock = new ReentrantLock();
    private Condition notEmpty = lock.newCondition();
    private Condition notFull = lock.newCondition();

    public void put(String message) throws InterruptedException {
        lock.lock();
        try {
            if (queue.size() == max) {
                notFull.await();
            }
            queue.add(message);
            notEmpty.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public String poll() throws InterruptedException {
        lock.lock();
        try {
            if (queue.size() == 0) {
                notEmpty.await();
            }
            String item = queue.remove();
            notFull.signalAll();
            return item;
        } finally {
            lock.unlock();
        }
    }


}
